package com.iflytek.iot.common.utils;

import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 网络工具
 * @author yu 2019/4/25.
 */
public class NetUtils {

    private static String serverIp;

    static {
        InetAddress ia = null;
        try {
            ia = ia.getLocalHost();
            serverIp = ia.getHostAddress();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取服务器的ip地址
     * @return
     */
    public static String getServerIp() {
        return serverIp;
    }


    /**
     * 根据网卡地址获取ip v4地址
     * @param nic
     * @return
     */
    public static String getIPV4ByNIC(String nic){
        return getLocalIPV4().get(nic);
    }

    /**
     * 根据网卡地址获取ip v6地址
     * @param nic
     * @return
     */
    public static String getIPV6ByNIC(String nic){
        return getLocalIPV6().get(nic);
    }
    /**
     * 获取所有的网卡的ip v4地址,key为网卡地址，value为ip地址
     * @return
     */
    public static Map<String,String> getLocalIPV4(){
        Map<String,String> map = new HashMap<>();
        InetAddress ip = null;
        try {
            Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
            while (netInterfaces.hasMoreElements()) {
                NetworkInterface ni = netInterfaces.nextElement();
                Enumeration<InetAddress> ips = ni.getInetAddresses();
                while (ips.hasMoreElements()) {
                    ip = ips.nextElement();
                    if(ip instanceof Inet4Address){
                        map.put(ni.getName(),ip.getHostAddress());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 获取所有ipv6地址
     * @return
     */
    public static Map<String,String> getLocalIPV6(){
        Map<String,String> map = new HashMap<>();
        InetAddress ip = null;
        try {
            Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
            while (netInterfaces.hasMoreElements()) {
                NetworkInterface ni = netInterfaces.nextElement();
                Enumeration<InetAddress> ips = ni.getInetAddresses();
                while (ips.hasMoreElements()) {
                    ip = ips.nextElement();
                    if(ip instanceof Inet6Address){
                        map.put(ni.getName(),ip.getHostAddress());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
}
